<?php
include('lib/adodb-time.inc.php');

function sqlDate($shrt)
{
	if ($shrt == "") { return ""; }

	//preg_match_all('(\d+)\/(\d+)\/(\d+)',$shrt,$parts);
	preg_match_all('/(.*)\/(.*)\/(.*)/',$shrt,$parts);
	$month = $parts[1][0];
	$day   = $parts[2][0];
	$year = $parts[3][0];
	$err = "";
	if ($month < 1 || $month > 12) { $err = "month out of range ($month)"; }
	if ($day   < 1 || $day   > 31) { $err = "day out of range ($day)"; }
	if ($year < 30) { $year += 2000; }
	elseif ($year < 100) { $year += 1900; }
	if ($year < 1000 || $year > 2050) { $err = "year out of range ($year)"; }

	if ($err == "") {
		$isodate = sprintf("%04d-%02d-%02d",$year,$month,$day);
		return $isodate;
	} else {
		return "!$err";
	}
}

function dieErr($msg)
{
	global $id;

	header("Content: text/html");
	echo "
<html>
<body>
<h2>ERROR</h2>
<p>$msg</p>
<p>Record was not modified.</p>
<p><a href=\"person.php?id=$id\" title=\"Return\">Return to previous person</a>.</p>
</body>
</html>";
	exit(1);
}

function redirect($url)
{
	header("Location: $url");
	exit;
}

function AddParenttoChild($chID, $rel, $pID) {
	// after adding a new parent, enter the parent's ID on the child

	// CONNECT TO DB

	$clink = mysql_connect("localhost", "ftreemod", "ftree_mod")
	   or dieErr("Could not connect : " . mysql_error());
	mysql_select_db("ftree") or dieErr("Could not select database");

	if ($rel == "f") { $fld = "`father`"; } else { $fld = "`mother`"; }
	$query = "UPDATE `person` SET " . $fld . " = '" . $pID . "' WHERE `id` = '" . $chID . "'";
	$result = mysql_query($query) or dieErr("Query failed : " . mysql_error());
	mysql_close($clink);
}

function AddMarriage($oldSID, $newSID, $newSex) {
	// after adding a new spouse, add entry in marriage table

	// CONNECT TO DB

	$clink = mysql_connect("localhost", "ftreemod", "ftree_mod")
	   or dieErr("Could not connect : " . mysql_error());
	mysql_select_db("ftree") or dieErr("Could not select database");

	if ($newSex == "F") {
		$husband = $oldSID;
		$wife    = $newSID;
	} else { 
		$husband = $newSID;
		$wife    = $oldSID;
	}
	$query = "INSERT INTO `marriage` (`husband`, `wife`) VALUES ('" . $husband . "', '" . $wife . "')";
	$result = mysql_query($query) or dieErr("Query failed : " . mysql_error());
	mysql_close($clink);
}


// BEGIN MAIN

$postProc = "";

if ($_POST['Cancel'] == "Cancel") {
	redirect("person.php?id=${_POST['PersonID']}");
}

// CONNECT TO DB

$link = mysql_connect("localhost", "ftreemod", "ftree_mod")
   or dieErr("Could not connect : " . mysql_error());
mysql_select_db("ftree") or dieErr("Could not select database");

$id = $_POST['PersonID'];
$id=preg_replace("/[^0-9]/","",$id);  //get rid of anything but numbers
if ($id < 1 || $id > pow(2,17)) {
        dieErr("ID ($id) is out of range.");
}

if ($_POST['whichForm'] == "Personal") {

	$mapping = array(
			"NFirst"  => "first",
                        "NMiddle" => "middle",
                        "NLast"   => "last",
                        "NSuffix" => "suffix",
                        "NNick"   => "nick",
                        "Gender"  => "sex",
                        "DOB"   => "dob",
                        "POB"   => "pob",
                        "Birth" => "birth",
                        "DOD"   => "dod",
                        "POD"   => "pod",
                        "Death" => "death",
        );

	$query = "";
	$mode = $_POST['mode'];
	$dob = sqlDate($_POST['DOB']);
	if (substr($dob,0,1) == "!") {
		dieErr("DOB " . substr($dob,1));
	}
	$dod = sqlDate($_POST['DOD']);
	if (substr($dod,0,1) == "!") {
		dieErr("DOD " . substr($dod,1));
	}
	
	if ($mode == "a") {
		/*
		INSERT INTO `person` ( `id` , `first` , `middle` , `last` , `suffix` , `nick` , `sex` , `dob` , `pob` , `birth` , `dod` , `pod` , `death` , `father` , `mother` )
		VALUES (
			'', 'FName', 'MName', 'LName', 'SName', 'NName', 'M', '1965-05-10', 'POBirth', 'BirthNotes', '2065-05-10', 'PODeath', 'DeathNotes', '1111', '2222'
		);
		*/
		$query = "INSERT INTO `person` ";

		$fldNs = "";
		$fldVs = "";
		foreach ($mapping as $frmFld => $dbFld) {
			if     ($frmFld == "DOB") { $val = $dob; }
			elseif ($frmFld == "DOD") { $val = $dod; }
			else {
				$val = $_POST[$frmFld];
			}
			$fldNs .= "`$dbFld`, ";
			$fldVs .= "'$val', ";
		}
		$relation = $_POST['relation'];
		if ($relation == "c") {  // adding a child
			$addFID = $_POST['AddFID'];
			$addMID = $_POST['AddMID'];
			$fldNs .= "`father`, `mother` ";
			$fldVs .= "'" . $addFID . "', '" . $addMID . "'";
		} elseif ($relation == "f" || $relation == "m") {
	        	$fldNs = preg_replace("/\s*,\s*$/"," ",$fldNs);  //get rid of final ,
	        	$fldVs = preg_replace("/\s*,\s*$/"," ",$fldVs);  //get rid of final ,
			$postProc = "addptoc";
		} elseif ($relation == "s") {
	        	$fldNs = preg_replace("/\s*,\s*$/"," ",$fldNs);  //get rid of final ,
	        	$fldVs = preg_replace("/\s*,\s*$/"," ",$fldVs);  //get rid of final ,
			$postProc = "addmarriage";
		}
		$query .= "( $fldNs ) VALUES ( $fldVs )";

	} elseif ($mode == "w") {
		/*
		UPDATE `person` SET `pob` = 'POfBirth',
		`dod` = '2065-05-10',
		`pod` = 'POfDeath' WHERE `id` = '70196' LIMIT 1 ;
		*/
		$query = "UPDATE `person` SET ";
		
		foreach ($mapping as $frmFld => $dbFld) {
			if     ($frmFld == "DOB") { $val = $dob; }
			elseif ($frmFld == "DOD") { $val = $dod; }
			else {
				$val = $_POST[$frmFld];
			}
			$query .= "`$dbFld` = '$val', ";
		}
		
		$query = preg_replace("/\s*,\s*$/"," ",$query);  //get rid of final ,
		$query .= "WHERE `id` = '$id' LIMIT 1";
	}		
} elseif ($_POST['whichForm'] == "Parents") {

	$fID = $_POST['ChgFID'];
	$mID = $_POST['ChgMID'];

	$query = "SELECT `id` FROM `person` WHERE `id` = '$fID'";
	$result = mysql_query($query);
	$fndRows = mysql_num_rows($result);
	if ($fndRows < 1) { dieErr("ID $fID does not exist."); }
	mysql_free_result($result);

	$query = "SELECT `id` FROM `person` WHERE `id` = '$mID'";
	$result = mysql_query($query);
	$fndRows = mysql_num_rows($result);
	if ($fndRows < 1) { dieErr("ID $mID does not exist."); }
	mysql_free_result($result);

	$query  = "UPDATE `person` SET `father` = '$fID', `mother` = '$mID' ";
	$query .= "WHERE `id` = '$id'";

} elseif ($_POST['whichForm'] == "Spouse") {

	$mid = $_POST['MarriageID'];
	$dom = sqlDate($_POST['DOM']);
        if (substr($dom,0,1) == "!") {
                dieErr("DOM " . substr($dom,1));
        }
	$spMode = $_POST['SpMode'];
	if ($spMode == "add") {
		$psex = $_POST['PersonSex'];
		if ($psex == "M") {
			$hid = $id;
			$wid = $_POST['ChgSp'];
		} else {
			$wid = $id;
			$hid = $_POST['ChgSp'];
		}
		$query = "INSERT INTO `marriage` ( `husband` , `wife` , `date` , `place` , `notes` ) VALUES ( '$hid', '$wid', '$dom', '$_POST[POM]', '$_POST[Marriage]')";
	} else {  //edit

		$mapping = array(
	                        "DOM"      => "date",
	                        "POM"      => "place",
	                        "Marriage" => "notes",
	        );

	        $query = "UPDATE `marriage` SET ";
      
		foreach ($mapping as $frmFld => $dbFld) {
			if     ($frmFld == "DOM") { $val = $dom; }
			else {
				$val = $_POST[$frmFld];
			}
	                $query .= "`$dbFld` = '$val', ";
		}
      
	        $query = preg_replace("/\s*,\s*$/"," ",$query);  //get rid of final ,
	        $query .= "WHERE `id` = '$mid' LIMIT 1";
	}
} else {  //unknown form
	header("Content = text/plain");
	echo "Did not recognize form name (${_POST['whichForm']}). \n";
	echo "No changes made.\n";
	exit; 
}


//header("Content = text/plain");
//echo "$query\n\n";
//print_r($_POST);

if ($query != "") {
	$result = mysql_query($query) or dieErr("Query failed : " . mysql_error());

	if ($mode == "a") {
		$oldID = $id;
		$id = mysql_insert_id();
	}
}

// DISCONNECT DB

mysql_close($link);

switch ($postProc) {
case "addptoc":
	AddParenttoChild($oldID, $relation, $id);
	break;
case "addmarriage":
	AddMarriage($oldID, $id, $_POST['Gender']);
	break;
}

redirect("person.php?id=$id");
?>
